const db = wx.cloud.database()
const directionsCollection = db.collection('pc_directions')
const app = getApp()

Page({
  async onLoad(options){
    let res = await directionsCollection.get()
    console.log(res)
    let directions = res.data.map(v=>{
      return v.name
    })
    if(app.globalData.user.choosen.length==0){
      app.globalData.user.choosen = directions.slice(0)
    }
    this.setData({
      directions,
      user:app.globalData.user
    })
  },
  change(e){
    let choosen = this.data.user.choosen
    let picked = this.data.directions[Number(e.detail.value)]
    let found = choosen.indexOf(picked)
    console.log(found)
    if(found<e.currentTarget.dataset.id){
      wx.vibrateShort({
        type: 'light',
      })
      wx.showToast({
        title:`第${found+1}志愿已经选${picked}`,
        icon:'error'
      })
    }else{
      choosen.splice(e.currentTarget.dataset.id,0,picked)
      choosen.splice(choosen.lastIndexOf(picked),1)
    }
    let user = this.data.user
    user.choosen = choosen
    this.setData({
      user
    })
  },
  async post(e){
    let user = this.data.user
    let res = await wx.cloud.callFunction({
      name:'pc_post',
      data:{
        user
      }
    })
    console.log(res)
    if(res.result.res.errMsg.indexOf('ok')>0){
      wx.showToast({
        title: '提交成功',
      })
      wx.redirectTo({
        url: '/pages/work18/list/list',
      })
    }
  }
})